package com.paradogs.gs.modules;

import com.paradogs.common.utils.SpringUtils;
import com.paradogs.framework.annotations.ParadogsAnnotationsHolder;
import com.paradogs.framework.server.MessageHeader;
import com.paradogs.framework.server.ParadogsContext;
import com.paradogs.framework.server.ParadogsGameLogicHandleThread;
import com.paradogs.framework.server.ServerEvent;
import com.paradogs.framework.utils.ContextUtils;
import com.paradogs.gs.misc.PlayerSession;
import com.paradogs.gs.misc.SyncDataUpdater;
import com.paradogs.gs.utils.PlayerUtils;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: yumi
 * @date: 2024/10/16  15:05
 * @Description: TODO
 */
@Component
public class PlayerService {

    /** 玩家状态自动同步 */
    // OneMessageHandleAfterEvent 如果遇到 Update 更新的状态并且后续没新消息，会卡住
//    @EventListener(ServerEvent.OneMessageHandleAfterEvent.class)
    @EventListener(ServerEvent.ServerUpdateEvent.class)
    public void autoSyncData() {
        SyncDataUpdater.autoSync();
        SyncDataUpdater.clear();
    }

    /** 玩家断开连接 */
    @EventListener(ServerEvent.ClientLeaveEvent.class)
    public void onClientLeave(ServerEvent.ClientLeaveEvent event) {
        Object actorId = event.getChannel().attr(AttributeKey.valueOf("actor_id")).get();
        if (actorId == null) {
            return;
        }
        ParadogsGameLogicHandleThread.join(actorId.toString(), () -> {
            PlayerSession session = PlayerUtils.getSession(event.getChannel());
            if (session == null) { return; }
            // 模拟玩家 logout
            ParadogsGameLogicHandleThread.join(
                    actorId.toString(),
                    () -> session.getPlayer().kick()
            );
        });
    }

}
